from flask import Blueprint, render_template, request

from apps.pojo.Entity import User, UserSchema, db
from apps.util.LayData import LayData

user_bp = Blueprint('user', __name__, url_prefix='/user')
user_schema = UserSchema(many=True)


@user_bp.route('/tolist')
def to_list():
    return render_template('user/list.html')


@user_bp.route('/toadd')
def to_add():
    return render_template('user/add.html')


@user_bp.route('/addSave', methods=['POST'])
def add_save():
    user = User()
    user.username = request.form.get('username')
    user.password = request.form.get('password')
    try:
        db.session.add(user)
        db.session.commit()
        return LayData.data2(0, '添加成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '添加失败')


@user_bp.route('/toupdate/<int:id>')
def to_update(id):
    user = User.query.get(id)
    return render_template('user/update.html', user=user)


@user_bp.route('/delete/<int:id>', methods=['GET'])
def delete(id):
    user = User.query.get(id)
    db.session.delete(user)
    try:
        db.session.commit()
        return LayData.data2(0, '删除成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '删除失败')


@user_bp.route('/updateSave', methods=['POST'])
def update_save():
    user = User.query.get(request.form.get('id'))
    user.username = request.form.get('username')
    user.password = request.form.get('password')
    try:
        db.session.commit()
        return LayData.data2(0, '更新成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '更新失败')


@user_bp.route('/list')
def list():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    offset = (page - 1) * limit
    user_list = User.query.offset(offset).limit(limit).all()
    count = User.query.count()
    users = user_schema.dump(user_list)
    return LayData.data(0, 'success', count, users)
